package com.example.myletcodelearing.chaintable

import com.example.myletcodelearing.designlinkedlist.MyLinkedList

/**
 * @author tgw
 * @date 2022/7/30
 * @describe
 */
class CircleChainNode {


    var nextNode: CircleChainNode? = null


    var value: Int = -1

    override fun toString(): String {
        return "ChainNode(nextNode=$nextNode, value=$value)"
    }

}


fun main(array: Array<String>) {
    println("测试开始单向链表")
    val test = TestCircleChainNode()


    val head0 = CircleChainNode().apply {
        value = -1
    }

    test.insertNode(head0, 5, 0)
    test.insertNode(head0, 2, 0)
    test.insertNode(head0, 20, 1)
    test.deletdNode(head0,  1)
//    test.insertNode(head0, 3, 1)
//    print(head0)
    print( test.searchNode(head0,0))
}

private fun print(node: ChainNode) {
    println("打印${node.toString()}")
}

class TestCircleChainNode {

    var size =0

    fun insertNode(head: CircleChainNode, value: Int, index: Int) {

        var nextNode: CircleChainNode? = head
        var point = 0
        var hasFind = false
        while (nextNode != null) {
            if (index == point) {
                val insert = CircleChainNode().apply {
                    this.value = value
                }
                var preNode = nextNode.nextNode


                //代表到了表尾
                if (size==point){
                    preNode =  CircleChainNode().apply {
                        this.value = head.value
                    }
                }

                insert.nextNode = preNode
                nextNode.nextNode = insert
                hasFind = true
                size++
                break
            }
            point++
            nextNode = nextNode.nextNode

        }

        if (!hasFind){
            println("index $index 不存在越界")
        }

    }

    fun deletdNode(head: CircleChainNode, index: Int) {

        var nextNode: CircleChainNode? = head
        var point = 0
        var hasFind = false
        while (nextNode != null) {
            if (index == point) {
                val preNode = nextNode.nextNode?.nextNode
                nextNode.nextNode = preNode
                hasFind = true
                break
            }
            point++
            nextNode = nextNode.nextNode
        }

        if (!hasFind){
            println("index $index 不存在越界")
        }

    }

    fun searchNode(head: CircleChainNode, index: Int):CircleChainNode? {

        var nextNode: CircleChainNode? = head
        var point = 0
        var hasFind = false
        while (nextNode != null) {
            if (index == point) {
                hasFind = true
                return nextNode
            }
            point++
            nextNode = nextNode.nextNode

        }

        if (!hasFind){
            println("index $index 不存在越界")
        }
        return null
    }


}
